package com.snail.snailvr.views.fragments;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.snail.snailvr.R;
import com.snail.snailvr.event.BusProvider;
import com.snail.snailvr.utils.FileUtil;
import com.snail.snailvr.utils.IntentUtils;
import com.snail.snailvr.utils.LogUtils;
import com.snail.snailvr.views.ImagePreviewActivity;
import com.snail.snailvr.widget.FSSimpleImageView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.subjects.PublishSubject;

/**
 * 反馈
 * Created by Jason on 16/6/3.
 */
public class FeedbackFragment extends BaseToolbarFragment {

    private static final int MAX_PIC_COUNT = 5;

    @Bind(R.id.toolbar)
    Toolbar mToolbar;

    @Bind(R.id.stars)
    RatingBar stars;

    @Bind(R.id.email)
    EditText email;

    @Bind(R.id.images)
    LinearLayout images;

    @Bind(R.id.text_content)
    EditText text_content;

    @Bind(R.id.post)
    TextView post;

    private final String IMAGE_TYPE = "image/*";

    private final int IMAGE_CODE = 0;
    private final int PREVIEW_CODE = 2;

    private ArrayList<Uri> uriList;
    private ArrayList<String> pathList;

    private boolean hasStar = false;
    private boolean hasTextContent = false;
    private boolean hasImage = false;

    private static String saved_content;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusProvider.getInstance().register(this);
    }

    public FeedbackFragment() {
    }

    @Override
    protected void handleIntent() {
    }

    @Override
    protected void initView() {
        post.setClickable(false);

        setupToolbar(mToolbar, getResources().getString(R.string.feedback), -1);

        View root = LayoutInflater.from(getActivity()).inflate(R.layout.feedback_image, null);
        root.setOnClickListener(getALbumListener);
        ImageView add_view = (FSSimpleImageView) root.findViewById(R.id.image);
        add_view.setImageResource(R.drawable.ic_feedback_add);
        images.addView(root);

        uriList = new ArrayList<>(MAX_PIC_COUNT);
        pathList = new ArrayList<>(MAX_PIC_COUNT);

        text_content.setText(saved_content);
        if (!TextUtils.isEmpty(saved_content)){
            hasTextContent = true;
            refreshPostButton();
        }

        final PublishSubject<String> publishSubject = PublishSubject.create();
        publishSubject.debounce(400, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if(0 == s.length()){
                    hasTextContent = false;
                }
                else{
                    hasTextContent = true;
                }

                refreshPostButton();
            }
        });

        text_content.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                publishSubject.onNext(s.toString());
            }
        });

        stars.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
                if(0 == v){
                    hasStar = false;
                }
                else{
                    hasStar = true;
                }

                refreshPostButton();
            }
        });
    }

    private void refreshPostButton(){
        if (hasImage || hasStar || hasTextContent){
            post.setBackgroundResource(R.drawable.feedback_post_blue);
            post.setClickable(true);
        }
        else{
            post.setBackgroundResource(R.drawable.feedback_post_grey);
            post.setClickable(false);
        }
    }

    private View.OnClickListener getALbumListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // 使用intent调用系统相册
            Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
            getAlbum.setType(IMAGE_TYPE);
            startActivityForResult(getAlbum, IMAGE_CODE);
        }
    };

    private View.OnClickListener previewListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = ImagePreviewActivity.getIntent(getActivity(), (Serializable) uriList);
            startActivityForResult(intent, PREVIEW_CODE);
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != getActivity().RESULT_OK) {// 此处的 RESULT_OK 是系统自定义得一个常量
            LogUtils.e("ActivityResult resultCode error");
            return;
        }

        if (requestCode == IMAGE_CODE) {
            Uri originalUri = data.getData();// 获得图片的uri
            uriList.add(originalUri);
            // 拿到图片
            hasImage = true;
            refreshPostButton();

            // 显示得到的bitmap图片
            if (images.getChildCount() <= 4) {
                View root = LayoutInflater.from(getActivity()).inflate(R.layout.feedback_image, null);
                root.setOnClickListener(previewListener);
                FSSimpleImageView image = (FSSimpleImageView) root.findViewById(R.id.image);
                image.setImageURI(originalUri);
                images.addView(root, images.getChildCount() - 1);
            } else {
                View root = images.getChildAt(images.getChildCount() - 1);
                root.setOnClickListener(previewListener);
                FSSimpleImageView image = (FSSimpleImageView) root.findViewById(R.id.image);
                image.setImageURI(originalUri);
            }

            String path= FileUtil.getPath(getContext(), originalUri);
            if(!TextUtils.isEmpty(path))
                pathList.add(path);

        } else if (requestCode == PREVIEW_CODE) {
            // 清空后重新加载一遍
            images.removeAllViews();
            pathList.clear();
            uriList = (ArrayList<Uri>) data.getSerializableExtra(ImagePreviewActivity.URI_KEY);

            if (0 == uriList.size()){
                hasImage = false;
            }
            else{
                hasImage = true;
            }
            refreshPostButton();

            for (Uri uri : uriList){
                View root = LayoutInflater.from(getActivity()).inflate(R.layout.feedback_image, null);
                root.setOnClickListener(previewListener);
                FSSimpleImageView image = (FSSimpleImageView) root.findViewById(R.id.image);
                image.setImageURI(uri);
                images.addView(root);

                String path = FileUtil.getPath(getContext(), uri);
                if (!TextUtils.isEmpty(path))
                    pathList.add(path);
            }

            if (images.getChildCount() <= 4) {
                View root = LayoutInflater.from(getActivity()).inflate(R.layout.feedback_image, null);
                root.setOnClickListener(getALbumListener);
                ImageView add_view = (FSSimpleImageView) root.findViewById(R.id.image);
                add_view.setImageResource(R.drawable.ic_feedback_add);
                images.addView(root);
            }

        }
    }

    @Override
    protected void loadData() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_feedback;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusProvider.getInstance().unregister(this);

        saved_content = text_content.getText().toString();
    }

    @Override
    protected boolean onToolbarMenuItemClick(MenuItem item) {
        return false;
    }

    @OnClick(R.id.post)
    public void post() {
        int score = (int)stars.getRating()*2;
        String content = text_content.getText().toString();
        String mail = email.getText().toString();
        IntentUtils.feedBackPost(getActivity(), score, pathList, content, mail);
        getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new FeedbackOKFragment()).commitAllowingStateLoss();

        text_content.setText("");
    }
}
